<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8"/>
    <meta content="width=device-width, initial-scale=1.0" name="viewport"/>
    <title>YXD 轨道监控系统（WebSocket + AJAX 版）</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
            overflow: hidden;
            background-color: #f9fafb;
        }

        .log-container {
            height: 100%;
            overflow-y: auto;
            background: #1e293b;
            color: #f1f5f9;
            padding: 10px;
            border-radius: 6px;
            font-family: 'Courier New', monospace;
            font-size: 13px;
            line-height: 1.4;
        }

        .highlight {
            animation: pulse 1.5s infinite;
        }

        @keyframes pulse {
            0% {
                box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.6);
            }
            70% {
                box-shadow: 0 0 0 8px rgba(239, 68, 68, 0);
            }
            100% {
                box-shadow: 0 0 0 0 rgba(239, 68, 68, 0);
            }
        }
    </style>
</head>
<body class="text-gray-800">
<div class="flex h-screen w-screen p-4 gap-4">
    <!-- 左侧：日志区 -->
    <div class="flex-1 bg-white rounded-lg shadow flex flex-col">
        <h2 class="text-lg font-semibold px-4 pt-3">实时日志（WebSocket 动态更新）</h2>
        <div class="flex-1 mt-2 mx-4 mb-4">
            <div class="log-container" id="logContainer">
                <!-- 日志内容将通过 WebSocket 动态插入此处 -->
            </div>
        </div>
    </div>

    <!-- 右侧：产线配置与轨道状态 -->
    <div class="w-96 bg-white rounded-lg shadow p-4 flex-shrink-0 flex flex-col">
        <h2 class="text-lg font-semibold mb-3">产线配置</h2>
        <select class="w-full p-2 border border-gray-300 rounded mb-3" id="laneSelect">
            <option value="">-- 请选择产线 --</option>
            <option value="1">YXD-1轨</option>
            <option value="2">YXD-2轨</option>
        </select>
        <div class="text-sm space-y-1 text-gray-700 mt-2" id="configDisplay">
            <p class="text-gray-500 italic text-sm">请选择一个产线查看详细配置</p>
        </div>
        <button class="mt-4 bg-indigo-600 text-white p-2 rounded hover:bg-indigo-700" id="fetchStatusBtn">获取轨道状态
        </button>
        <div class="mt-4 text-sm space-y-1 text-gray-700" id="statusDisplay">
            <p class="text-gray-500 italic text-sm">轨道状态信息将显示在此处</p>
        </div>
    </div>
</div>

<script>
    // WebSocket 部分
    const wsUrl = 'ws://localhost:8080/logs'; // 根据你的服务器地址调整
    const socket = new WebSocket(wsUrl);

    socket.onopen = () => {
        console.log('WebSocket 连接已建立');
    };

    socket.onmessage = (event) => {
        const logContainer = document.getElementById('logContainer');
        const logEntry = document.createElement('div');
        logEntry.className = 'mb-2';
        logEntry.innerHTML = event.data; // 假设后端发送的数据格式为 HTML 或纯文本
        logContainer.appendChild(logEntry);
        logContainer.scrollTop = logContainer.scrollHeight; // 自动滚动到底部
    };

    socket.onclose = () => {
        console.log('WebSocket 连接关闭');
    };

    socket.onerror = (error) => {
        console.error('WebSocket 错误:', error);
    };

    // AJAX 获取轨道状态部分
    document.getElementById('fetchStatusBtn').addEventListener('click', function () {
        const laneNo = document.getElementById('laneSelect').value;
        if (!laneNo) {
            alert('请先选择一个产线');
            return;
        }

        fetch(`http://localhost:7777/api/lane/${laneNo}/status`)
            .then(response => response.json())
            .then(data => {
                const statusDisplay = document.getElementById('statusDisplay');
                let html = '';
                if (data.success) {
                    html += `<p><span class="font-medium">轨道编号:</span> ${data.laneNo}</p>`;
                    html += `<p><span class="font-medium">PLC IP:</span> ${data.ip}</p>`;
                    html += `<p><span class="font-medium">传感器状态:</span> ${data.sensorStatus ? '正常' : '异常'}</p>`;
                    html += `<p><span class="font-medium">正面扫码器:</span> ${data.scanner.front.status} (${data.scanner.front.code})</p>`;
                    html += `<p><span class="font-medium">反面扫码器:</span> ${data.scanner.back.status} (${data.scanner.back.code})</p>`;
                } else {
                    html = '<p class="text-red-500">获取失败，请稍后再试。</p>';
                }
                statusDisplay.innerHTML = html;
            })
            .catch(error => {
                console.error('请求失败:', error);
                document.getElementById('statusDisplay').innerHTML = '<p class="text-red-500">网络错误，请检查连接。</p>';
            });
    });

    // 产线配置选择事件
    document.getElementById('laneSelect').addEventListener('change', function (e) {
        const laneNo = e.target.value;
        const display = document.getElementById('configDisplay');
        if (!laneNo) {
            display.innerHTML = '<p class="text-gray-500 italic text-sm">请选择一个产线查看详细配置</p>';
            return;
        }

        // 模拟的配置数据，实际应用中应从服务器获取
        const cfg = {
            1: {
                laneNo: 1,
                ip: "192.168.10.101",
                sensorAddress: "40001",
                panelAddress: "40002",
                scanner: [
                    {position: "正面", ip: "192.168.10.201"},
                    {position: "反面", ip: "192.168.10.202"}
                ]
            },
            2: {
                laneNo: 2,
                ip: "192.168.10.102",
                sensorAddress: "40003",
                panelAddress: "40004",
                scanner: [
                    {position: "正面", ip: "192.168.10.203"},
                    {position: "反面", ip: "192.168.10.204"}
                ]
            }
        }[laneNo];

        let html = `
        <p><span class="font-medium">轨道编号:</span> YXD-${cfg.laneNo}</p>
        <p><span class="font-medium">PLC IP:</span> ${cfg.ip}</p>
        <p><span class="font-medium">传感器寄存器:</span> ${cfg.sensorAddress}</p>
        <p><span class="font-medium">面板寄存器:</span> ${cfg.panelAddress}</p>
        <p class="mt-2"><span class="font-medium">扫码器:</span></p>
        <ul class="list-disc pl-5 mt-1 space-y-1 text-sm">
      `;
        cfg.scanner.forEach(s => {
            html += `<li>${s.position}扫码器: ${s.ip}</li>`;
        });
        html += '</ul>';
        display.innerHTML = html;
    });
</script>
</body>
</html>